import React, {useState, useEffect} from 'react';
import Taro from '@tarojs/taro';
import {View, Input} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import './number-input.scss'

const NumberInput: React.FC<{ showMaxToast?: boolean; canZero?: string; val: number; index?: any; step?: number; min?: number; max?: number; disabled?: boolean; thisChange?: any }> = (props: any) => {
  const [step, setStep] = useState(1)
  const [disabled, setDisabled] = useState(false)
  const [blurtime, setBlurtime] = useState({val: 0, time: 0})

  useEffect(() => {
    setBlurtime({
      val: props.val > 0 ? props.val : props.canZero ? 0 : 1,
      time: 1,
    })
    setStep(props.step)
  }, [props.step, props.index, props.val, props.canZero])

  useEffect(() => {
    setDisabled(props.disabled)
  }, [props.disabled])

  const handleChange = (type) => {
    if (!disabled) {
      let val = blurtime.val
      if (type) {
        if (val < (props.max || 999)) {
          val = val + step
        }
      } else {
        if ((props.min || 0) < val) {
          val = val - step
          if (val <= 0) {
            val = 0
          }
        }
      }
      setBlurtime({
        val,
        time: 1,
      })
      props.thisChange(val)
    }
  }

  const blur = (e) => {
    let num: any = Number(e.detail.value)
    if (!num) {
      num = props.min
    } else {
      if (num > props.max) {
        num = props.max
        if (props.showMaxToast) {
          Taro.showToast({
            title: '该商品最多购买' + props.max + '件',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
    setBlurtime({
      val: num,
      time: blurtime.time + 1,
    })
    props.thisChange(num)
  }

  return (
    <View className={props.disabled ? "number-input--disabled number-input" : "number-input"}>
      <View className={`number-input ${props.disabled && "number-input--disabled"}`}>
        <View onClick={handleChange.bind(this, 0,)}
          className={(props.min < blurtime.val) ? "number__btn" : "number__btn number--disabled"}
        ><AtIcon
          value='subtract' size='12' customStyle='font-size: 12px'
        /></View>
        <Input className='num-input' value={blurtime.val + blurtime.time - blurtime.time} type='number' onBlur={blur}
          disabled={disabled}
        />
        <View onClick={handleChange.bind(this, 1)}
          className={(props.max > blurtime.val) ? "number__btn" : "number__btn number--disabled"}
        ><AtIcon
          value='add' size='12' customStyle='font-size: 12px'
        /></View>
      </View>
    </View>
  )
}
NumberInput.defaultProps = {
  val: 1,
  min: 0,
  index: 0,
  step: 1,
  max: 999,
  showMaxToast: true,
  disabled: false
}

export default NumberInput

